//
//  FileManagementTwoViewController.m
//  Againstpoor
//
//  Created by 辰领科技 on 16/11/6.
//  Copyright © 2016年 yuf. All rights reserved.
//

#import "FileManagementTwoViewController.h"
#import "FileManagementTwoTableViewCell.h"
#import "InformationDetailsViewController.h"
static NSString * Identifer = @"identifier";

@interface FileManagementTwoViewController ()
<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate> {
    BOOL isSelected;
    NSInteger _totle;
}
@property (nonatomic,assign)   NSInteger    pageNO;

@property (weak, nonatomic) IBOutlet UIView *navView;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UITextField *textField;
@property (weak, nonatomic) IBOutlet UIButton *search;
@property (weak, nonatomic) IBOutlet UIButton *BGbutton;
@property (weak, nonatomic) IBOutlet UIButton *searchButton;
@property (strong, nonatomic) NSMutableArray *array;
@end

@implementation FileManagementTwoViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    isSelected = YES;
    _textField.alpha = 0.0f;
    _search.alpha = 0.0f;
    _BGbutton.alpha = 0.0f;
    [self.tableView.header beginRefreshing];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _array = [NSMutableArray array];
    [self initViewLayout];
    [self addRefreshing];
}
- (void)initViewLayout{
    [self adaptiveViewLayout:self.view];
    [self adaptiveViewLayout:self.navView];
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    
    _textField.layer.masksToBounds = YES;
    _textField.layer.cornerRadius = 12.5*VerticalRatio();
    _textField.leftView = [[UIView alloc]initWithFrame:flexibleFrame(CGRectMake(0, 0, 10, 1), NO)];
    _textField.leftViewMode = UITextFieldViewModeAlways;
    [_textField setValue:kGetColor(156, 156, 156) forKeyPath:@"_placeholderLabel.textColor"];
    
    _textField.delegate = self;
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    self.name = textField.text;
    [self getListfilesmanagement];
    textField.text = @"";
    [textField resignFirstResponder];
    return YES;
}

- (IBAction)back:(id)sender {
    [self backBtn];
}

#pragma mark -- 添加刷新数据
- (void)addRefreshing{
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        int64_t delayInSeconds = 8.0;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self.tableView.header endRefreshing];
        });
        self.pageNO = 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            [self getListfilesmanagement];
        });
    }];
    [_tableView.header beginRefreshing];
}
//加载更多数据
- (void)loadMoreData{
    if (self.array.count == _totle) {
        [self.tableView.footer endRefreshing];
    }else{
        self.pageNO = self.pageNO + 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            [self getListfilesmanagement];
        });
    }
}


#pragma mark - 档案管理列表
- (void)getListfilesmanagement {
    NSMutableDictionary * dic = [NSMutableDictionary dictionary];
    [dic setObject:[NSString stringWithFormat:@"%d",_pageNO] forKey:@"pageNum"];
    [dic setObject:[NSString stringWithFormat:@"%d",PageSize] forKey:@"pageSize"];
    
    if (_area) {
        [dic setObject:_area forKey:@"area"];
    }
    if (_name) {
        [dic setObject:_name forKey:@"name"];
    }
    
    self.shareApi.delegate = self;
    [self.shareApi  requestOperationWithDic:dic withPath:F_farmerList withHttpType:@"POST" withTag:F_F_farmerList];
}
#pragma mark - 搜索
- (IBAction)search:(id)sender {
    isSelected = !isSelected;
    if (isSelected) {
        [UIView animateWithDuration:0.5 animations:^{
            _textField.alpha = 0.0f;
            _search.alpha = 0.0f;
            _BGbutton.alpha = 0.0f;
        }];
        [_searchButton setImage:[UIImage imageNamed:@"fangdajing1.png"] forState:UIControlStateNormal];
        [_searchButton setTitle:@"" forState:UIControlStateNormal];
    } else {
        [UIView animateWithDuration:0.5 animations:^{
            _textField.alpha = 1.0f;
            _search.alpha = 1.0f;
            _BGbutton.alpha = 1.0f;
        }];
        [_searchButton setImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
        [_searchButton setTitle:@"取消" forState:UIControlStateNormal];
        _textField.text = @"";
    }
}
- (IBAction)hidden:(id)sender {
    [UIView animateWithDuration:0.5 animations:^{
        _textField.alpha = 0.0f;
        _search.alpha = 0.0f;
        _BGbutton.alpha = 0.0f;
    }];
    [_searchButton setImage:[UIImage imageNamed:@"fangdajing1.png"] forState:UIControlStateNormal];
    [_searchButton setTitle:@"" forState:UIControlStateNormal];
}

#pragma mark - <UITableViewDelegate&&UITableViewDataSource>
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

//定义 UITableView cell 的个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _array.count;
    
}

//定义 UITableView cell 的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 95*VerticalRatio();
}

//定义 UITableView cell 展示的内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    FileManagementTwoTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:Identifer];
    if (cell == nil) {
        cell= [[FileManagementTwoTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:Identifer];
        
    }
    for (UIView *view in cell.subviews) {
        if ([view isKindOfClass:[UILabel class]] ||[view isKindOfClass:[UIImageView class]]||[view isKindOfClass:[UIScrollView class]]||[view isKindOfClass:[UIButton class]]) {
            [view removeFromSuperview];
        }
    }
    NSDictionary *dic = _array[indexPath.row];
    
    NSString *image = [NSString stringWithFormat:@"%@",dic[@"image"]];
    if (image && image.length>0 && ![dic[@"image"] isEqual:[NSNull null]]) {
        [cell.image sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",IP_Address_ImageDown_Fresh,image]]];
    }
    
    cell.nameLabel.text = [NSString stringWithFormat:@"贫困户：%@",dic[@"NAME"]];
    NSInteger AAB003 = [dic[@"AAB003"] integerValue];
    if (AAB003 == 1) {
        cell.genderLabel.text = @"性别：男";
    } else if (AAB003 == 2) {
        cell.genderLabel.text = @"性别：女";
    }
    
    cell.ageLabel.text = [NSString stringWithFormat:@"年龄：%@",dic[@"AGE"]];
    cell.ethnicLabel.text = [NSString stringWithFormat:@"名族：%@",[self ethnic:[NSString stringWithFormat:@"%@",dic[@"AAB007"]]]];
    cell.levelLabel.text = [NSString stringWithFormat:@"文化程度：%@",[self RecordOfFormalSchooling:[NSString stringWithFormat:@"%@",dic[@"AAB008"]]]];
    cell.addressLabel.text = [NSString stringWithFormat:@"地址：%@",dic[@"ADDRESS"]];
    
    return cell;
}

//定义 UITableView cell 点击事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"HomePageStoryboard" bundle:nil];
    InformationDetailsViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"InformationDetails"];
    page.AAC001 = [Common stringFromData:_array[indexPath.row][@"AAC001"]];
    [[Common getNavigation]pushViewController:page];
}

#pragma   mark---- GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
    [_tableView.footer endRefreshing];
    [_tableView.header endRefreshing];
    if (tag==F_F_farmerList) {
        
        if (  [[database valueForKey:@"flag"] integerValue]!=1 ) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                _totle = [database[@"total"] integerValue];
                if (_totle > PageSize) {
                    __weak __typeof(self) weakSelf = self;
                    if (!self.tableView.footer) {
                        // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
                        self.tableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                            [weakSelf loadMoreData];
                        }];
                    }
                }
                if (self.pageNO == 1) {
                    [self.array removeAllObjects];
                }
                
                NSArray *arr = database[@"rows"];
                for (id entity in arr) {
                    [self.array addObject:entity];
                }
                _tableView.dataSource = self;
                _tableView.delegate = self;
                [_tableView reloadData];
            });
        }else  {
            
        }
    }
}
-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
    
    [_tableView.footer endRefreshing];
    [_tableView.header endRefreshing];
    [self dismissWaitDialog];
    
}

- (NSString *)ethnic:(NSString *)value {
    NSString *str;
    if([value isEqualToString:@"01"]) {
        str = @"汉族";
    }else if([value isEqualToString:@"02"]) {
        str = @"满族";
    }else if([value isEqualToString:@"03"]) {
        str = @"回族";
    }else if([value isEqualToString:@"04"]) {
        str = @"蒙古族";
    }else if([value isEqualToString:@"05"]) {
        str = @"藏族";
    }else if([value isEqualToString:@"06"]) {
        str = @"维吾尔族";
    }else if([value isEqualToString:@"07"]) {
        str = @"苗族";
    }else if([value isEqualToString:@"08"]) {
        str = @"彝族";
    }else if([value isEqualToString:@"09"]) {
        str = @"壮族";
    }else if([value isEqualToString:@"10"]) {
        str = @"布依族";
    }else if([value isEqualToString:@"11"]) {
        str = @"朝鲜族";
    }else if([value isEqualToString:@"12"]) {
        str = @"侗族";
    }else if([value isEqualToString:@"13"]) {
        str = @"瑶族";
    }else if([value isEqualToString:@"14"]) {
        str = @"白族";
    }else if([value isEqualToString:@"15"]) {
        str = @"土家族";
    }else if([value isEqualToString:@"16"]) {
        str = @"哈尼族";
    }else if([value isEqualToString:@"17"]) {
        str = @"哈萨克族";
    }else if([value isEqualToString:@"18"]) {
        str = @"傣族";
    }else if([value isEqualToString:@"19"]) {
        str = @"黎族";
    }else if([value isEqualToString:@"20"]) {
        str = @"僳僳族";
    }else if([value isEqualToString:@"21"]) {
        str = @"佤族";
    }else if([value isEqualToString:@"22"]) {
        str = @"畲族";
    }else if([value isEqualToString:@"23"]) {
        str = @"高山族";
    }else if([value isEqualToString:@"24"]) {
        str = @"拉祜族";
    }else if([value isEqualToString:@"25"]) {
        str = @"水族";
    }else if([value isEqualToString:@"26"]) {
        str = @"东乡族";
    }else if([value isEqualToString:@"27"]) {
        str = @"纳西族";
    }else if([value isEqualToString:@"28"]) {
        str = @"景颇族";
    }else if([value isEqualToString:@"29"]) {
        str = @"柯尔克孜族";
    }else if([value isEqualToString:@"30"]) {
        str = @"土族";
    }else if([value isEqualToString:@"31"]) {
        str = @"达斡尔族";
    }else if([value isEqualToString:@"32"]) {
        str = @"仫佬族";
    }else if([value isEqualToString:@"33"]) {
        str = @"羌族";
    }else if([value isEqualToString:@"34"]) {
        str = @"布朗族";
    }else if([value isEqualToString:@"35"]) {
        str = @"撒拉族";
    }else if([value isEqualToString:@"36"]) {
        str = @"毛南族";
    }else if([value isEqualToString:@"37"]) {
        str = @"仡佬族";
    }else if([value isEqualToString:@"38"]) {
        str = @"锡伯族";
    }else if([value isEqualToString:@"39"]) {
        str = @"阿昌族";
    }else if([value isEqualToString:@"40"]) {
        str = @"普米族";
    }else if([value isEqualToString:@"41"]) {
        str = @"塔吉克族";
    }else if([value isEqualToString:@"42"]) {
        str = @"怒族";
    }else if([value isEqualToString:@"43"]) {
        str = @"乌孜别克族";
    }else if([value isEqualToString:@"44"]) {
        str = @"俄罗斯族";
    }else if([value isEqualToString:@"45"]) {
        str = @"鄂温克族";
    }else if([value isEqualToString:@"46"]) {
        str = @"德昂族";
    }else if([value isEqualToString:@"47"]) {
        str = @"保安族";
    }else if([value isEqualToString:@"48"]) {
        str = @"裕固族";
    }else if([value isEqualToString:@"49"]) {
        str = @"京族";
    }else if([value isEqualToString:@"50"]) {
        str = @"塔塔尔族";
    }else if([value isEqualToString:@"51"]) {
        str = @"独龙族";
    }else if([value isEqualToString:@"52"]) {
        str = @"鄂伦春族";
    }else if([value isEqualToString:@"53"]) {
        str = @"赫哲族";
    }else if([value isEqualToString:@"54"]) {
        str = @"门巴族";
    }else if([value isEqualToString:@"55"]) {
        str = @"珞巴族";
    }else if([value isEqualToString:@"56"]) {
        str = @"基诺族";
    }else if([value isEqualToString:@"99"]) {
        str = @"其他";
    }
    return str;
}

- (NSString *)RecordOfFormalSchooling:(NSString *)value {
    NSString *str;
    if([value isEqualToString:@"01"]) {
        str = @"文盲或半文盲";
    }else if([value isEqualToString:@"02"]) {
        str = @"小学";
    }else if([value isEqualToString:@"03"]) {
        str = @"初中";
    }else if([value isEqualToString:@"04"]) {
        str = @"高中";
    }else if([value isEqualToString:@"05"]) {
        str = @"大专及以上";
    }else if([value isEqualToString:@"06"]) {
        str = @"学龄前儿童";
    }
    return str;
}
@end
